package com.globo.opensocial;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class Content {

	protected File file;	
	protected InputStream inputStream;
	protected Application app;

	/**
	 * Constructor
	 */
	Content(Application app, File file) {
		
		this.file = file;		
		this.app = app;
		
		assert file != null;
	}
	
	Content(Application app, InputStream inputStream) {		
		this.inputStream = inputStream;		
		this.app = app;
		
		assert inputStream != null;
	}

	/**
	 * Dummy processline function
	 * 
	 * @param input
	 * @return
	 */
	public String processLine(String input) {
		return input;
	}

	/**
	 * Returns the content.
	 * 
	 * @return
	 * @throws FileDontExists
	 */
	public String getContent() throws FileNotFoundException {
		StringBuffer out = new StringBuffer();
		
		try {
						
			InputStream stream;
						
			//read from file or stream
			if(file != null) {
				System.err.println("[INFO] Reading " + file.getName());
				stream = new FileInputStream(file);
			} else {
				stream = inputStream;
			}
			
			BufferedReader in = new BufferedReader(new InputStreamReader(stream, app.getChaset()));
			
			String line = "";
			while ((line = in.readLine()) != null) {
				out.append(processLine(line));
				out.append("\n");
			}
			out.append("\n");
			return out.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
}
